package historymanager.servlets;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

import historymanager.model.ControllerUnit;
import historymanager.model.MeasurePoint;
import historymanager.model.Measure;
import historymanager.model.MeasurePointList;
import historymanager.model.MeasurePointListCO;
import historymanager.model.MeasureTimeSeries;
import historymanager.tools.Configuration;

/**
 * Servlet implementation class DataProvider
 * <p>
 * Serves data for many different purpose in the server-ui-interface. Preferred
 * data-interchange-format is: JSON
 * <p>
 * <p>
 * Changes 1.1:<br/>
 * - Connection open/close eauch time, a request occurs <br/>
 * - Some more debug-messages...<br/>
 * Change1 1.2:<br/>
 * - Calculate a special "modulo-parameter" that limits the number of relevant
 * measures per measureseries in method sendResponseGetMeasure
 * 
 * @author Thomas Aulich
 * @version 1.1
 *
 */

public class DataProvider extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Logger log = Logger.getLogger(DataProvider.class);
	private Context context;
	private Configuration configuration;
	private DataSource dataSource;

	// private Connection connection;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DataProvider() {
		super();
		log.debug("Servlet construction ...");
		configuration = Configuration.getInstance();
		log.debug("... Configuration loaded ...");
		try {
			context = new InitialContext();
			dataSource = (DataSource) context.lookup(configuration
					.getDataSourceContext());
		} catch (NamingException e) {
			log.error("InitialContext could not be loaded ...");
			e.printStackTrace();
		}
		log.debug("DataProvider() finished ...");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("doGet() was called; Querystring:" + request.getQueryString());
		String mode = request.getParameter("mode");
		if (mode == null) {
			response.sendError(400, "Missing mode-parameter!");
		} else {
			mode = mode.toLowerCase();
			log.debug("mode-parameter of request is: " + mode);
			switch (mode) {
			case "getmeasurepoint":
				sendResponseGetMeasurePoint(request, response);
				break;
			case "getmeasure":
				sendResponseGetMeasure(request, response);
				break;
			case "getmeasurepointlist":
				sendResponseGetMeasurePointList(request, response);
				break;
			case "deletemeasurepointlist":
				deleteMeasurePointList(request, response);
				break;
			case "getmeasurepointlistlink":
				sendResponseGetMeasurePointListLink(request, response);
				break;
			case "getcsvdownload":
				getCSVDownLoad(request, response);
				break;
			case "showlogfiles":
				showLogFiles(request, response);
				break;
			case "showlogfile":
				showLogFile(request, response);
				break;
			default:
				response.sendError(400, "Invalid mode-parameter!");
				log.error("HTTP400: Invalid mode-parameter!");
			}
		}
		log.debug("doGet() finished ...");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("doPost() was called; Querystring="
				+ request.getQueryString());
		String mode = request.getParameter("mode");
		if (mode == null) {
			response.sendError(400, "Missing mode-parameter!");
		} else {
			mode = mode.toLowerCase();
			log.debug("mode-parameter of request is: " + mode);
			switch (mode) {
			case "setmeasurepointlist":
				setMeasurePointList(request, response);
				break;
			default:
				response.sendError(400, "Invalid mode-parameter!");
				log.error("HTTP400: Invalid mode-parameter!");
			}
		}
		log.debug("doPost() finished ...");
	}

	/**
	 * Delete a measurepoint list ...
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void deleteMeasurePointList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("deleteMeasurePointList() was called ...");
		String id = request.getParameter("id");
		log.debug("Measurepointlist to delete: id=" + id);
		if (id == null) {
			response.sendError(400, "Missing id-parameter in delete-request!");
		} else {
			String SQLString = "";
			try {
				Connection connection = dataSource.getConnection();
				Statement statement = connection.createStatement();
				// Delete all linked measurepoints
				SQLString = "delete from measurepointlistlink where measurepointlist = "
						+ id;
				statement.executeUpdate(SQLString);
				// Now delete the measurepointlist
				SQLString = "delete from measurepointlist where id = " + id;
				statement.executeUpdate(SQLString);
				statement.close();
				connection.close();
				log.debug("Connection closed ...");
			} catch (SQLException e) {
				log.error("Error with dtabase-operation:" + e.getMessage()
						+ ", SQLString=" + SQLString);
				e.printStackTrace();
				response.sendError(500, "SQL-Error: " + e.getMessage());
			}
		}
		log.debug("deleteMeasurePointList() finished ...");
	}

	/**
	 * Performs POST-requests to save or update a MeasurePointList
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void setMeasurePointList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("setMeasurePointList() was called ...");
		// Get the necessary information from data-parameter
		String json = request.getParameter("data");
		String SQLString = "";
		log.debug("Information to process: " + json);
		// De-serialize the string to the corresponding object
		Gson gson = new Gson();
		MeasurePointListCO measurePointListCO = gson.fromJson(json,
				MeasurePointListCO.class);
		if (measurePointListCO.getId() == null) {
			// Mode is 'new'
			if (measurePointListCO.getName() == null
					|| measurePointListCO.getName().trim().equals("")) {
				// Missing name
				response.sendError(400,
						"Missing name-parameter in new-request!");
			} else {
				try {
					Connection connection = dataSource.getConnection();
					Statement statement = connection.createStatement();
					SQLString = "insert into measurepointlist (name) values('"
							+ measurePointListCO.getName() + "')";
					statement.executeUpdate(SQLString);
					// Get the id of this new list
					SQLString = "select id from measurepointlist where name ='"
							+ measurePointListCO.getName()
							+ "' order by lastusage desc";
					ResultSet resultSet = statement.executeQuery(SQLString);
					if (resultSet.next()) {
						// Loop around all corresponding Measure-Points
						long id = resultSet.getLong("id");
						for (int i = 0; i < measurePointListCO
								.getMeasurePointIdsSize(); i++) {
							SQLString = "insert into measurepointlistlink (measurepointlist, measurepoint) values("
									+ String.valueOf(id)
									+ ","
									+ String.valueOf(measurePointListCO
											.getMeasurePointId(i)) + ")";
							statement.executeUpdate(SQLString);
						}
					}
					statement.close();
					connection.close();
					log.debug("Connection closed ...");
				} catch (SQLException e) {
					log.error("Error with dtabase-operation:" + e.getMessage()
							+ ", SQLString=" + SQLString);
					e.printStackTrace();
					response.sendError(500, "SQL-Error: " + e.getMessage());
				}
			}
		} else {
			// Mode is 'update'
			if (measurePointListCO.getId() == null
					|| measurePointListCO.getId().trim().equals("")) {
				// Missing id
				response.sendError(400,
						"Missing id-parameter in update-request!");
			} else {
				try {
					Connection connection = dataSource.getConnection();
					Statement statement = connection.createStatement();
					// At first delete all (eventually) existing records ...
					SQLString = "delete from measurepointlistlink where measurepointlist = "
							+ measurePointListCO.getId();
					statement.executeUpdate(SQLString);
					// Now (re)create all records for this
					// measurepointlist...
					for (int i = 0; i < measurePointListCO
							.getMeasurePointIdsSize(); i++) {
						SQLString = "insert into measurepointlistlink (measurepointlist, measurepoint) values("
								+ measurePointListCO.getId()
								+ ","
								+ String.valueOf(measurePointListCO
										.getMeasurePointId(i)) + ")";
						statement.executeUpdate(SQLString);
					}
					statement.close();
					connection.close();
					log.debug("Connection closed ...");
				} catch (SQLException e) {
					log.error("Error with dtabase-operation:" + e.getMessage()
							+ ", SQLString=" + SQLString);
					e.printStackTrace();
					response.sendError(500, "SQL-Error: " + e.getMessage());
				}
			}

		}
		log.debug("List-id:" + measurePointListCO.getId());
		log.debug("setMeasurePointList() finished ...");
	}

	/**
	 * Delivers data about measure-points.
	 * <p>
	 * Possible parameters:
	 * <p>
	 * id: just a specific measurepoint requested
	 * <p>
	 * controllerunitid: Measurepoints of a specific ControllerUnit requested
	 * <p>
	 * <none>: all MeasurePoints requested
	 * <p>
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void sendResponseGetMeasurePoint(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("sendResponseGetMeasurePoint() was called ...");
		try {
			Connection connection = dataSource.getConnection();
			Statement statement = connection.createStatement();
			String SQLString = new String();
			// Check, if specific measurepoint requested
			String id = request.getParameter("id");
			Long idValue;
			if (id != null) {
				idValue = Long.parseLong(id);
				SQLString = "SELECT * FROM measurepoint AS mp, "
						+ "controllerunit AS cu "
						+ "WHERE mp.controllerunit = cu.id " + "AND mp.id ="
						+ String.valueOf(idValue);
			} else {
				// Check, if specific controllerunit
				String controllerunitid = request
						.getParameter("controllerunitid");
				if (controllerunitid != null) {
					idValue = Long.parseLong(controllerunitid);
					SQLString = "SELECT * FROM measurepoint AS mp, "
							+ "controllerunit AS cu "
							+ "WHERE mp.controllerunit = cu.id "
							+ "AND mp.controllerunit ="
							+ String.valueOf(idValue);
				} else {
					// All measurepoints are requested ...
					SQLString = "SELECT * FROM measurepoint AS mp, "
							+ "controllerunit AS cu "
							+ "WHERE mp.controllerunit = cu.id";
				}
			}
			ResultSet resultSet = statement.executeQuery(SQLString);
			log.debug("Running query to select all measurepoints ...");
			List<MeasurePoint> list = new ArrayList<MeasurePoint>();
			while (resultSet.next()) {
				ControllerUnit controllerUnit = new ControllerUnit(
						resultSet.getLong("cu.id"), resultSet.getString(
								"cu.serveraddress").trim(), resultSet
								.getString("cu.stationname").trim(), resultSet
								.getString("cu.stationalias").trim(),
						resultSet.getInt("cu.active"));
				MeasurePoint measurePoint = new MeasurePoint(
						resultSet.getLong("id"), controllerUnit, resultSet
								.getString("mp.symbolname").trim(), resultSet
								.getString("mp.aliasname").trim(), resultSet
								.getString("mp.type").trim(),
						resultSet.getInt("mp.registeraddress"), resultSet
								.getString("mp.format").trim(),
						resultSet.getInt("mp.decimaldigits"), resultSet
								.getString("mp.unit").trim());
				list.add(measurePoint);
			}
			statement.close();
			connection.close();
			log.debug("Connection closed ...");
			Gson gson = new Gson();
			response.setHeader("Content-Type",
					"application/json; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(list));
			log.debug("JSON-stream put in 'out.print'...");
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(500, "SQL-Error: " + e.getMessage());
		}
		log.debug("sendResponseGetMeasurePoint() finished ...");
	}

	/**
	 * Delivers a measureseries for a specific measurepoint.
	 * <p>
	 * Possible parameters:
	 * <p>
	 * measurepointid: must have: specified measure-point
	 * <p>
	 * startat: start-date/time of measureseries
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void sendResponseGetMeasure(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("sendResponseGetMeasure() was called ...");
		// Check, if specific measurepoint requested
		String measurepointid = request.getParameter("measurepointid");
		if (measurepointid == null) {
			response.sendError(400, "Parameter 'measurepointid' is missing!");
		} else {
			try {
				Configuration configuration = Configuration.getInstance();
				String limitString = String.valueOf(configuration
						.getMaxMeasureValuesPerResultSet());
				Connection connection = dataSource.getConnection();
				Statement statement = connection.createStatement();
				String SQLString = new String();

				Long idValue = Long.parseLong(measurepointid);
				// Get ControllerUnit & Measurepoint for this measurepointid
				SQLString = "SELECT * FROM measurepoint AS mp, "
						+ "controllerunit AS cu "
						+ "WHERE mp.controllerunit = cu.id " + "AND mp.id ="
						+ String.valueOf(idValue);
				ControllerUnit controllerUnit = null;
				MeasurePoint measurePoint = null;
				ResultSet resultSet = statement.executeQuery(SQLString);
				if (resultSet.next()) {
					controllerUnit = new ControllerUnit(
							resultSet.getLong("cu.id"), resultSet.getString(
									"cu.serveraddress").trim(), resultSet
									.getString("cu.stationname").trim(),
							resultSet.getString("cu.stationalias").trim(),
							resultSet.getInt("cu.active"));
					measurePoint = new MeasurePoint(resultSet.getLong("id"),
							controllerUnit, resultSet
									.getString("mp.symbolname").trim(),
							resultSet.getString("mp.aliasname").trim(),
							resultSet.getString("mp.type").trim(),
							resultSet.getInt("mp.registeraddress"), resultSet
									.getString("mp.format").trim(),
							resultSet.getInt("mp.decimaldigits"), resultSet
									.getString("mp.unit").trim());

				}
				MeasureTimeSeries measureTimeSeries = new MeasureTimeSeries();
				measureTimeSeries.setMeasurePoint(measurePoint);
				String datefrom = request.getParameter("datefrom");
				String dateto = request.getParameter("dateto");
				// New since 25.03.2015:
				// Calculate a modulo-parameter ...
				int moduloParameter = 1;
				long measureRequestInterval = configuration
						.getMeasureRequestInterval();
				int maxMeasurePointsPerSeries = configuration
						.getMaxMeasurePointsPerSeries();
				try {
					Date fromDate = new SimpleDateFormat("yyyy-MM-dd")
							.parse(datefrom);
					Date toDate = new SimpleDateFormat("yyyy-MM-dd")
							.parse(dateto);
					long timeDif = toDate.getTime() - fromDate.getTime();
					if (timeDif > 0) {
						long cycleCount = timeDif / measureRequestInterval;
						moduloParameter = (int) (cycleCount / maxMeasurePointsPerSeries);
						log.debug("Calculated time difference between datefrom/dateto: "
								+ String.valueOf(timeDif)
								+ "; Number of cycles: "
								+ String.valueOf(cycleCount)
								+ "; moduloParameter: "
								+ String.valueOf(moduloParameter));
					}
				} catch (ParseException e) {
					log.error("Problems to convert request-date-parameters to valid date-values: "
							+ e.getMessage()
							+ ". Cannot calculate modulo-parameter");
				}
				// Prevent, that modulo becomes smaller than 1...
				if (moduloParameter < 1){
					moduloParameter = 1;
				}
				// Now get requested measure-series
				SQLString = "SELECT * FROM measure WHERE measurepoint = " + String.valueOf(measurePoint.getId())
						+ " and MOD(msid, "
						+ String.valueOf(moduloParameter)
						+ ") = 0 ";
						
				// Check for parameters 'datefrom' and 'dateto'
				if (datefrom != null) {
					SQLString += " AND date(at) >= '" + datefrom + "'";
				}
				if (dateto != null) {
					SQLString += " AND date(at) <= '" + dateto + "'";
				}
				SQLString += " ORDER BY at LIMIT " + limitString;
				log.debug("Executog SQL:" + SQLString);
				resultSet = statement.executeQuery(SQLString);
				Measure measure;
				log.debug("Running query to get measure-series: " + SQLString);
				while (resultSet.next()) {
					measure = new Measure(resultSet.getLong("id"),
							measurePoint, resultSet.getDouble("val"),
							resultSet.getTimestamp("at"));
					measureTimeSeries.addMeasure(measure);
				}
				statement.close();
				connection.close();
				log.debug("Connection closed ...");
				Gson gson = new Gson();
				response.setHeader("Content-Type",
						"application/json; charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.print(gson.toJson(measureTimeSeries));
				log.debug("JSON-stream put in 'out.print'...measureTimeSeries.getSize()=" + String.valueOf(measureTimeSeries.getSize()));
			} catch (SQLException e) {
				e.printStackTrace();
				response.sendError(500, "SQL-Error: " + e.getMessage());
			}
		}
		log.debug("sendResponseGetMeasure() finished ...");
	}

	/**
	 * Delivers a list of all MeasurePoints, connected to a specific
	 * MeasurePointList
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void sendResponseGetMeasurePointListLink(
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		log.debug("sendResponseGetMeasurePointListLink was called...");
		String id = request.getParameter("id");
		if (id == null) {
			response.sendError(400, "Missing id-parameter.");
			log.error("HTTP-400 Missing id-parameter.");
		} else {
			try {
				Connection connection = dataSource.getConnection();
				Statement statement = connection.createStatement();
				String SQLString = new String();
				SQLString = "SELECT * FROM measurepointlistlink where measurepointlist = "
						+ id;
				ResultSet resultSet = statement.executeQuery(SQLString);
				log.debug("Running query to select all measurepoints for a measurepointlist ...");
				List<String> list = new ArrayList<String>();
				while (resultSet.next()) {
					list.add(String.valueOf(resultSet.getLong("measurepoint")));
				}
				log.debug("Number of measurepoints for measurepointlist " + id
						+ ": " + String.valueOf(list.size()));
				// Finally update the timestamp in that record
				SQLString = "update measurepointlist set lastusage= now() where id = "
						+ id;
				statement.execute(SQLString);
				statement.close();
				connection.close();
				log.debug("Connection closed ...");
				Gson gson = new Gson();
				response.setHeader("Content-Type",
						"application/json; charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.print(gson.toJson(list));
				log.debug("JSON-stream put in 'out.print'...");

			} catch (SQLException e) {
				e.printStackTrace();
				response.sendError(500, "SQL-Error: " + e.getMessage());
			}
		}
		log.debug("sendResponseGetMeasurePointListLink() finished ...");
	}

	/**
	 * Delivers a list of all known MeasurePointList(s)
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void sendResponseGetMeasurePointList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("sendResponseGetMeasurePointList() was called ...");
		try {
			Connection connection = dataSource.getConnection();
			Statement statement = connection.createStatement();
			String SQLString = new String();
			SQLString = "SELECT * FROM measurepointlist ORDER BY lastusage DESC";
			ResultSet resultSet = statement.executeQuery(SQLString);
			log.debug("Running query to select all measurepointlists ...");
			List<MeasurePointList> list = new ArrayList<MeasurePointList>();
			while (resultSet.next()) {
				MeasurePointList measurePointList = new MeasurePointList(
						resultSet.getLong("id"), resultSet.getString("name"),
						resultSet.getTimestamp("lastUsage"));
				list.add(measurePointList);
			}
			statement.close();
			connection.close();
			log.debug("Connection closed ...");
			Gson gson = new Gson();
			response.setHeader("Content-Type",
					"application/json; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(list));
			log.debug("JSON-stream put in 'out.print'...");
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(500, "SQL-Error: " + e.getMessage());
		}
		log.debug("sendResponseGetMeasurePointList() finished ...");
	}

	/**
	 * Sends data as CSV
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void getCSVDownLoad(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("getCSVDownLoad() was called ...");
		String idListString = request.getParameter("idlist");
		String SQLString = "";
		try {
			Connection connection = dataSource.getConnection();
			Statement statement = connection.createStatement();
			SQLString = "SELECT m.id AS id, " + "cu.serveraddress, "
					+ "cu.stationname, " + "cu.stationalias, "
					+ "cu.active AS cuactive, " + "mp.symbolname, "
					+ "mp.aliasname, " + "mp.registeraddress, " + "mp.unit, "
					+ "mp.active AS mpactive, " + "m.at, " + "m.val "
					+ "FROM measure AS m, " + "measurepoint AS mp, "
					+ "controllerunit AS cu " + "WHERE m.measurepoint = mp.id "
					+ "AND mp.controllerunit = cu.id " + "AND measurepoint IN "
					+ idListString;
			// Check for parameters 'datefrom' and 'dateto'
			String datefrom = request.getParameter("datefrom");
			if (datefrom != null) {
				SQLString += " AND date(at) >= '" + datefrom + "'";
			}
			String dateto = request.getParameter("dateto");
			if (dateto != null) {
				SQLString += " AND date(at) <= '" + dateto + "'";
			}

			try {
				OutputStream outputStream = response.getOutputStream();
				String headLine = "id;serveraddress;stationname;stationalias;cuactive;symbolname;aliasname;registeraddress;unit;mpactive;at;val\n";
				outputStream.write(headLine.getBytes());
				ResultSet resultSet = statement.executeQuery(SQLString);
				log.debug("Running query to select all measures for CSV-export: "
						+ SQLString);
				response.setContentType("text/csv");
				response.setHeader("Content-Disposition",
						"attachment; filename=data.csv");
				String outputResult = "";
				while (resultSet.next()) {
					outputResult = String.valueOf(resultSet.getLong("id"))
							+ ";";
					outputResult += resultSet.getString("serveraddress") + ";";
					outputResult += resultSet.getString("stationname") + ";";
					outputResult += resultSet.getString("stationalias") + ";";
					outputResult += String.valueOf(resultSet
							.getBoolean("cuactive")) + ";";
					outputResult += resultSet.getString("symbolname") + ";";
					outputResult += resultSet.getString("aliasname") + ";";
					outputResult += resultSet.getString("registeraddress")
							+ ";";
					outputResult += resultSet.getString("unit") + ";";
					outputResult += String.valueOf(resultSet
							.getBoolean("mpactive")) + ";";
					outputResult += String
							.valueOf(resultSet.getTimestamp("at")) + ";";
					outputResult += String.valueOf(resultSet.getDouble("val"))
							.replaceAll("\\.", "\\,") + ";";
					outputResult += "\n";
					outputStream.write(outputResult.getBytes());
				}
				resultSet.close();
			} catch (Exception e) {
				log.error(e.toString());
			}
			statement.close();
			connection.close();
			log.debug("Connection closed ...");
			log.debug("OutPut managed...");
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(500, "SQL-Error: " + e.getMessage());
		}
		log.debug("getCSVDownLoad() finished ...");
	}

	protected void showLogFiles(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("showLogFiles() was called");
		String outPut = "";
		String logFilePathString = configuration.getLogfilePath();
		File logFilePath = new File(logFilePathString);
		DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
		if (logFilePath.exists()) {
			outPut += "<table border='1' cellspacing='2' cellpadding='5'>"
					+ "<tr><td>Filename</td><td>Last modified</td>"
					+ "<td>Size [byte]</td></tr>";
			File[] listOfFiles = logFilePath.listFiles();
			for (File file : listOfFiles) {
				if (file.isFile()) {
					Date date = new Date(file.lastModified());
					outPut += "<tr><td><a href='DataProvider?mode=showlogfile&filename="
							+ file.getName()
							+ "'>"
							+ file.getName()
							+ "</a></td><td>"
							+ df.format(date)
							+ "</td><td>"
							+ String.valueOf(file.length()) + "</td></tr>";
				}
			}
			outPut += "</table>";
		} else {
			outPut = "Configured logfilepath doesn't exist: "
					+ logFilePathString;
			log.warn("outPut");
		}
		request.setAttribute("servletresponse", outPut);
		request.getRequestDispatcher("log.jsp").forward(request, response);
	}

	protected void showLogFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.debug("showLogFile() was called");
		String fileName = request.getParameter("filename");
		String outPut = "";
		if (fileName == null) {
			outPut += "Missing parameter: filename";
		} else {
			String logFileString = configuration.getLogfilePath()
					+ File.separator + fileName;
			File logFile = new File(logFileString);
			if (logFile.exists()) {
				outPut += "File exists.";
				try (BufferedReader br = new BufferedReader(new FileReader(
						logFile))) {
					String line;
					while ((line = br.readLine()) != null) {
						outPut += line + "<br/>";
					}
				} catch (Exception e) {
					log.error("Error while file reading: " + e.getMessage());
					outPut += "<br/>Error while file reading: "
							+ e.getMessage();
				}
			} else {
				outPut = "Logfile doesn't exist: " + logFileString;
				log.warn("outPut");
			}
		}
		request.setAttribute("servletresponse", outPut);
		request.getRequestDispatcher("log.jsp").forward(request, response);
	}

}
